import time
import requests
import json
import pandas as pd

API_KEY = "app-URHlbr4Ax7n3Kt1i9IYx4us2"
BASE_URL = "http://8.136.111.93:8008/v1"
USER_ID = "localhost-rzj"


def send_chat_message(
    supplement=None,
    type=None,
    difficulty=None,
    conversation_id=None,
    response_mode="blocking",
    courseName=None,
    knowledgeList=None
):

    url = f"{BASE_URL}/chat-messages"
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "query": "placeholder",
        "user": USER_ID,
        "response_mode": response_mode
    }

    if conversation_id:
        payload["conversation_id"] = conversation_id

    inputs_data = {}
    # 添加新的字段
    if supplement:
        inputs_data["supplement"] = supplement
    if courseName:
        inputs_data["courseName"] = courseName

    if type:
        inputs_data["type"] = type
    if difficulty:
        inputs_data["difficulty"] = difficulty

    if knowledgeList:
        inputs_data["knowledgeList"] = knowledgeList

    if inputs_data:
        payload["inputs"] = inputs_data
        # 打印 request 的 payload
        print("Request payload:", json.dumps(payload, indent=4))

    try:
        resp = requests.post(url, headers=headers, json=payload)
        resp.raise_for_status()
        return resp.json()
    except requests.exceptions.HTTPError as e:
        print("HTTP Error:", e)
        # 修改为使用 resp.text 获取响应内容
        print("Response content:", resp.text)
    except Exception as e:
        print("Error:", e)
    return None


if __name__ == "__main__":
    # 需要执行的 n 列表
    n_list = [60]
    # 给定的自定义参数
    type = "简答题"
    difficulty = "中等"
    courseName = "高等数学"
    supplement = ""
    knowledgeList = "导数的定义、导数的应用"

    for n in n_list:
        print(f"\n===== 正在执行 n = {n} 的循环请求 =====")

        # 本次 n 的结果列表
        results_list = []
        # 记录脚本开始时间
        script_start_time = time.time()

        print("=== 第 1 次请求：新建会话 ===")
        start_time = time.time()

        # 第一次请求：让后端新建会话
        result1 = send_chat_message(
            supplement=supplement,
            courseName=courseName,
            type=type,
            difficulty=difficulty,
            knowledgeList=knowledgeList
        )

        end_time = time.time()
        elapsed1 = end_time - start_time

        if not result1:
            print("第一次请求失败，无法获取 conversation_id")
            continue

        # 获取第一个 conversation_id 和回答
        conv_id = result1.get("conversation_id")
        answer1 = result1.get("answer", "")
        print("返回 conversation_id:", conv_id)
        print("answer1:", answer1)
        print(f"第 1 次请求耗时: {elapsed1:.3f} 秒\n")

        # 把本次信息存起来
        results_list.append({
            "RequestIndex": 1,
            "conversation_id": conv_id,
            "answer": answer1,
            "elapsed_time_s": round(elapsed1, 3)
        })

        # 后续请求：使用同一个 conversation_id
        for i in range(2, n+1):
            print(f"=== 第 {i} 次请求 ===")
            start_t = time.time()

            result = send_chat_message(
                supplement=supplement,
                type=type,
                difficulty=difficulty,
                conversation_id=conv_id
            )

            end_t = time.time()
            elapsed = end_t - start_t

            if result:
                answer = result.get("answer", "")
                print("answer:", answer)
                print(f"第 {i} 次请求耗时: {elapsed:.3f} 秒\n")

                results_list.append({
                    "RequestIndex": i,
                    "conversation_id": conv_id,
                    "answer": answer,
                    "elapsed_time_s": round(elapsed, 3)
                })
            else:
                print(f"第 {i} 次请求失败，跳过收集。")

        # 总耗时
        script_end_time = time.time()
        total_time = script_end_time - script_start_time
        print(f"=== n = {n} 全部请求完成，总耗时: {total_time:.3f} 秒 ===\n")

        excel_file = f"repeat_test{n}.xlsx"

        # 如果有结果，写Excel
        if results_list:
            df = pd.DataFrame(results_list)
            df.to_excel(excel_file, index=False)
            print(
                f"已成功将 n={n} 的 {len(results_list)} 条回复(含耗时)写入 Excel: {excel_file}")
        else:
            print(f"n={n} 没有成功请求结果，不写 Excel。")
